
const { getHashValue, validateFields } = require('../public/util.js')
const { successMsg, errorMsg,page, security_key } = require('../public/constant.js')
const {executeTransaction}=require('../mysql/public.js')
const pool = require('../mysql/mysql.js');
const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer();
const jwt = require('jsonwebtoken')
const path=require('path')
const fs=require('fs')

const tableName='admin'

// 登录
router.post('/Login', upload.none(), validateFields([
  { field: 'userId', noEmpty: true, validType: 'string' },
  { field: 'password', noEmpty: true, validType: 'string' }
]), (req, res, next) => {
  const { userId, password } = req.body;
  // 参数1: 生成到token中的信息
  // 参数2: 密钥
  // 参数3: token的有效时间: 60, "2 days", "10h", "7d"
  const sql = `SELECT * FROM ${tableName} WHERE user_id=? and is_delete=0`
  pool.query(sql, [userId], (err, result) => {
    if (err){
      return res.status(500).send(errorMsg('数据库错误'));
    }
    // 将解密后的password（buffer）转为字符串
    var r = [...result]
    if (r.length) {
      const [storedSalt, storedHash] = r[0].password.split(":");
      const hashedPassword = getHashValue(password, storedSalt)
      if (hashedPassword == r[0].password) {
        const token = jwt.sign({ userId }, security_key, { expiresIn: '7d' })
        res.status(200).send(successMsg(token));
      } else {
        res.status(200).send(errorMsg('密码错误'))
      }
    } else {
      res.status(200).send(errorMsg('没有该用户'))
    }

  });
});

// 添加用户
router.post('/Add', upload.none(), validateFields([
  { field: 'userId', noEmpty: true, validType: 'string' },
  { field: 'password', noEmpty: true, validType: 'string' },
  { field: 'userName', noEmpty: true, validType: 'string' },
  { field: 'roleId', noEmpty: false, validType: 'string' },
  { field: 'photo', noEmpty: false, validType: 'string' },
]), (req, res) => {
  const { userId, password,userName,roleId,photo } = req.body;
  const saltedHash = getHashValue(password)
  executeTransaction({pool,res,queries:[
    {
      sql:`SELECT * FROM ${tableName} WHERE user_id=? and is_delete=0`,
      params:[userId],
      stopFlag:(result)=>result.length,
      stopEvent:()=>{res.status(200).send(errorMsg('用户Id重复'))}
    },
    {
      sql:`INSERT INTO ${tableName} (user_id, password,user_name,role_id,photo) VALUES (?, ?,?,?,?)`,
      params:[userId, saltedHash,userName,roleId||'role_2',photo||'/uploads/file-1702950541890.jpg'],
      successEvent:()=>{res.status(200).send(successMsg())}
    }
  ]})
});
// 修改用户信息
router.post('/Edit', upload.none(), validateFields([
  { field: 'userId', noEmpty: true, validType: 'string' },
  { field: 'userName', noEmpty: true, validType: 'string' },
  { field: 'roleId', noEmpty: true, validType: 'string' },
  { field: 'photo', noEmpty: true, validType: 'string' },
]), (req, res) => {
  const { userId,roleId,photo, userName } = req.body;
  executeTransaction({pool,res,queries:[
    {
      sql:`SELECT * FROM ${tableName} WHERE user_id=? and is_delete=0`,
      params:[userId],
      stopFlag:(result)=>!result.length,
      stopEvent:()=>{res.status(200).send(errorMsg('没有该用户'))}
    },
    {
      sql:`UPDATE ${tableName} SET user_name=?,role_id=?,photo=? WHERE user_id=?`,
      params:[userName,roleId,photo, userId],
      successEvent:()=>{res.status(200).send(successMsg())}
    }
  ]})
});
// 查询数据
router.get('/List', (req, res) => {
  pool.query(`SELECT ${tableName}.*,role.role_name FROM ${tableName} inner join role on ${tableName}.role_id=role.role_id where ${tableName}.is_delete=0`, (err, result) => {
    if (err){
      return res.status(500).send(errorMsg('数据库错误'));
    }
    var r = [...result]
    res.status(200).send(successMsg(r));
  });
});
// 查询数据
router.post('/PageList',upload.none(), (req, res) => {
  let {pageSize,pageIndex,roleId}=req.body
  pageSize=pageSize||10
  pageIndex=pageIndex||1
  let conditionSql=''
  const arr=[pageSize,(pageIndex-1)*pageSize]
  if(roleId){
    conditionSql+=` and ${tableName}.role_id=?`
    arr.unshift(roleId)
    arr.push(roleId)
  }
  const sql=`SELECT ${tableName}.*, role.role_name  FROM ${tableName} INNER JOIN role ON ${tableName}.role_id = role.role_id WHERE ${tableName}.is_delete = 0${conditionSql} LIMIT ? OFFSET ?; SELECT COUNT(*) FROM ${tableName} WHERE is_delete = 0${conditionSql}`
  pool.query(sql,arr,(err, result) => {
    if (err){
      console.log(err)
      return res.status(500).send(errorMsg('数据库错误'));
    }
    res.status(200).send(successMsg(page({data:result[0],total:result[1][0]['COUNT(*)'],pageIndex})));
  });
});
// 获取某一个用户
router.post('/GetOne', upload.none(), validateFields([
  { field: 'userId', noEmpty: true, validType: 'string' },
]), (req, res) => {
  const { userId } = req.body
  const sql = `SELECT ${tableName}.*,role.role_name FROM ${tableName} INNER JOIN role ON ${tableName}.role_id = role.role_id WHERE ${tableName}.user_id=? and ${tableName}.is_delete=0`
  pool.query(sql, [userId], (err, result) => {
    if (err){
      return res.status(500).send(errorMsg('数据库错误'));
    }
    // 将解密后的password（buffer）转为字符串
    var r = [...result]
    res.status(200).send(successMsg(r[0]))
  })
});
// 删除
router.get('/Delete', (req, res) => {
  const { userId } = req.query
  if (!userId) {
      return res.status(200).send(errorMsg('缺少参数userId'));
  }
  executeTransaction({pool,res,queries:[
    {
      sql:`SELECT * FROM ${tableName} WHERE user_id=?`,
      params:[userId],
      stopFlag:(result)=>!result.length,
      stopEvent:()=>{res.status(200).send(errorMsg('无效id'))}
    },
    {
      sql:`UPDATE ${tableName} SET is_delete=1 WHERE user_id=?`,
      params:[userId],
      successEvent:(result)=>{
        const filePath = path.join(__dirname, '../assets/uploads', result[0].photo.replace('/uploads/', ''));
        fs.unlink(filePath, function (err) {
            if (err) {
                console.log(err);
            } else {
                console.log('Successfully deleted file: ' + filePath);
            }
        });
        res.status(200).send(successMsg('操作成功'));
      }
    }
  ]})
});

// 修改密码
router.post('/EditPassword', upload.none(), validateFields([
  { field: 'userId', noEmpty: true, validType: 'string' },
  { field: 'password', noEmpty: true, validType: 'string' },
  { field: 'oldPassword', noEmpty: true, validType: 'string'},
]), (req, res) => {
  const { userId, password, oldPassword } = req.body;
  let saltedHash=''
  executeTransaction({pool,res,queries:[
    {
      sql:`SELECT * FROM ${tableName} WHERE user_id=? and is_delete=0`,
      params:[userId],
      stopFlag:(result)=>!result.length,
      stopEvent:()=>{res.status(200).send(errorMsg('没有该用户'))}
    },
    {
      sql:`UPDATE ${tableName} SET password=? WHERE user_id=?`,
      params:[saltedHash, userId],
      precheck:(params,result)=>{
        const [storedSalt, storedHash] = result[0].password.split(":");
        const hashedPassword = getHashValue(oldPassword, storedSalt)
        return hashedPassword == result[0].password
      },
      precheckEvent:()=>{
        res.status(200).send(errorMsg('原密码错误'))
      },
      modifyParamsEvent:(params,result)=>{
        const [storedSalt, storedHash] = result[0].password.split(":");
        const saltedHash = getHashValue(password, storedSalt)
        params[0]=saltedHash
        return params
      },
      successEvent:()=>{res.status(200).send(successMsg('修改密码成功'));}
    }
  ]})
});
module.exports = router;